<?php

namespace app\api\controller\v1;

use app\common\lib\ArrClass;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Toutiao;
use app\common\model\MallGoods;
use app\common\model\MallMessage;
use app\common\model\MallOrder;
use app\common\model\MallPaylog;
use app\common\model\MallUser;
use think\facade\Log;

class Login extends Base
{
    /**
     * @return \think\response\Json
     */
    public function getUserInfo()
    {
        $code = $this->request->param('code', '', 'trim');
        $anonymousCode = $this->request->param('anonymousCode', '', 'trim');

        try{
            $toutiaoInfo = Toutiao::getInstance()->code2Session($code,$anonymousCode);
        }catch (\Exception $e){
            Log::error("login_auth:" . Show::json_encode($toutiaoInfo));
            return Show::json_show(Status::mini_error, "系统内部错误");
        }

        if ($toutiaoInfo['err_no']>0) {
            Log::error("login_auth:" . Show::json_encode($toutiaoInfo));
            return Show::json_show(Status::mini_error, "系统内部错误");
        }
        if (empty($toutiaoInfo['data']['openid'])) {
            return Show::json_show(Status::mini_error, "程序错误");
        }
        $withoutField = 'delete_time,update_time';
        try {
            $res = (new MallUser())->where('openid', $toutiaoInfo['data']['openid'])
                ->withoutField($withoutField)
                ->find();
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "发生错误");
        }
        if ($res) {
            $result = $res->toArray();
            $messagecount= (new MallMessage())->getBaseByWhereCount([['touser','=',$result['openid']],['isread','=',0]]);
            $result['mcount'] =$messagecount;
        } else {
            try {
                $ret = (new MallUser())->save([
                    'openid' => $toutiaoInfo['data']['openid'],
                    'unionid' => $toutiaoInfo['data']['unionid'],
                    'idno'  =>Str::RandStr(7),
                    "type" => 0
                ]);
            } catch (\Exception $e) {
                return Show::json_show(Status::mini_error, "内部错误");
            }
            if ($ret) {
                try {
                    $res_data = (new MallUser())->where('openid', $toutiaoInfo['data']['openid'])
                        ->withoutField($withoutField)
                        ->find();
                } catch (\Exception $e) {
                    return Show::json_show(Status::mini_error, "发生错误");
                }
                if ($res_data) {
                    $result = $res_data->toArray();
                    $messagecount= (new MallMessage())->getBaseByWhereCount([['touser','=',$result['openid']],['isread','=',0]]);
                    $result['mcount'] =$messagecount;

                } else {
                    return Show::json_show(Status::mini_error, "数据不存在");
                }
            } else {
                return Show::json_show(Status::mini_error, "操作失败");
            }
        }

        return Show::json_show(Status::mini_normal, "ok", $result);
    }


    public function image(){
        if (!$this->request->isPost()) {
            throw new Exception("请求类型错误", 400);
        }
        $file = $this->request->file();
        if (empty($file)) {
            return Show::json_show(Status::mini_error, "请上传图片");
        }
        $key = array_keys($file);
        $arrType = ArrClass::uploadAttr();
        try {
            $objClass = ArrClass::initClass($key[0], $arrType, [], true);
            $res = $objClass->upload($this->request);
        }catch (\Exception $e){
            return Show::json_show(Status::mini_error,$e->getMessage(),[],400);
        }
        if($res){
            return Show::json_show(Status::mini_normal,"上传成功",[
                "url"=>(string)url('/'.$res,[],false,true)
            ]);// tp6自带全路径
        }else{
            return Show::json_show(Status::mini_error,'上传失败！请重试');
        }
    }

    public function notify(){
        $param =file_get_contents('php://input');
        $postdata =json_decode($param,true);
        if(isset($postdata['msg']) && !empty($postdata)){
            $responceOrder =json_decode($postdata['msg'],true);
            // 订单支付记录表
            $payorder =(new MallPaylog())->getBaseByWhereOne([['ordersn','=',$responceOrder['cp_orderno']]]);
            if($payorder && $payorder['status']==0 && ($responceOrder['total_amount'] == $payorder['money']*100)){
                // 更新订单记录
                (new MallPaylog())->where([['id','=',$payorder['id']]])->save(['status'=>1,'paytime'=>time()]);
                // 订单表
                $order =(new MallOrder())->find($payorder['order_id']);
                if($order){
                    (new MallOrder())->where([['id','=',$payorder['order_id']]])->save(['status'=>1,'pay_time'=>time(),'pay_type'=>$responceOrder['way']]);
                    // 添加销量
                    (new MallGoods())->where([['id','=',$order['goods_id']]])->Inc('sales',$order['goods_num'])->update();
                }
            }else{
                Log::error("payorder:" . Show::json_encode($payorder));
            }
            return true;
        }else{
            return false;
        }
    }
}